package study.concurrent.thread.auth;

import com.google.common.base.Stopwatch;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import study.concurrent.thread.support.session.UserContext;
import study.concurrent.thread.support.session.UserInfo;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
@Order(-100)
public class WatchdogFilter extends OncePerRequestFilter {

    private static final String X_REQUEST_ID = "X-Request-Id";

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        Stopwatch stopwatch = Stopwatch.createStarted();

        //request id
        String requestId = request.getHeader(X_REQUEST_ID);
        if (Strings.isNullOrEmpty(requestId)) {
            requestId = String.valueOf(System.currentTimeMillis());
        }
        //uri
        String uri = request.getRequestURI();
        UserContext.set(new UserInfo());
        MDC.put("request_id", requestId);
        try {
            //next filter
            doFilter(request, response, chain);
        } catch (Exception ex) {
            throw ex;
        } finally {
            log.info("[{}] cost time [{}] ms", uri, stopwatch.elapsed(TimeUnit.MILLISECONDS));
            MDC.clear();
//            UserContext.remove();
        }
    }
}
